<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebSocket连接调试工具</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background: #f5f5f5;
        }
        .container {
            background: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .status {
            padding: 10px;
            margin: 10px 0;
            border-radius: 5px;
            font-weight: bold;
        }
        .connected {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        .disconnected {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        .connecting {
            background: #fff3cd;
            color: #856404;
            border: 1px solid #ffeaa7;
        }
        .log {
            height: 400px;
            overflow-y: auto;
            border: 1px solid #ddd;
            padding: 10px;
            margin: 10px 0;
            background: #f9f9f9;
            font-family: monospace;
            font-size: 12px;
        }
        .controls {
            display: flex;
            gap: 10px;
            margin: 10px 0;
        }
        button {
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 14px;
        }
        .btn-primary {
            background: #007bff;
            color: white;
        }
        .btn-danger {
            background: #dc3545;
            color: white;
        }
        .btn-success {
            background: #28a745;
            color: white;
        }
        input[type="text"] {
            flex: 1;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🔧 WebSocket连接调试工具</h1>
        
        <!-- 连接状态 -->
        <div id="status" class="status disconnected">
            ❌ WebSocket未连接
        </div>
        
        <!-- 连接地址输入 -->
        <div class="controls">
            <input type="text" id="urlInput" value="ws://localhost:8123/api/ws/voice-chat" placeholder="WebSocket URL">
            <button id="connectBtn" class="btn-primary" onclick="connectWebSocket()">连接</button>
            <button id="disconnectBtn" class="btn-danger" onclick="disconnectWebSocket()" disabled>断开</button>
            <button class="btn-success" onclick="clearLog()">清空日志</button>
        </div>
        
        <!-- 日志显示区域 -->
        <div id="log" class="log"></div>
        
        <!-- 测试消息发送 -->
        <div class="controls">
            <input type="text" id="messageInput" placeholder="输入测试消息..." onkeypress="handleKeyPress(event)">
            <button class="btn-success" onclick="sendTestMessage()">发送测试消息</button>
        </div>
    </div>

    <script>
        let ws = null;
        let connectionAttempts = 0;
        const maxRetries = 3;

        // 添加日志
        function addLog(message, type = 'info') {
            const log = document.getElementById('log');
            const timestamp = new Date().toLocaleTimeString();
            const className = type === 'error' ? 'color: red' : type === 'success' ? 'color: green' : 'color: black';
            
            log.innerHTML += `<div style="${className}"><strong>[${timestamp}]</strong> ${message}</div>`;
            log.scrollTop = log.scrollHeight;
        }

        // 更新状态显示
        function updateStatus(text, className) {
            const status = document.getElementById('status');
            status.textContent = text;
            status.className = `status ${className}`;
        }

        // 连接WebSocket
        function connectWebSocket() {
            const url = document.getElementById('urlInput').value.trim();
            if (!url) {
                addLog('请输入WebSocket URL', 'error');
                return;
            }

            if (ws && ws.readyState === WebSocket.OPEN) {
                addLog('WebSocket已经连接，请先断开', 'error');
                return;
            }

            connectionAttempts++;
            addLog(`开始连接WebSocket (第${connectionAttempts}次尝试)...`);
            addLog(`URL: ${url}`);
            updateStatus('🔄 正在连接...', 'connecting');

            try {
                ws = new WebSocket(url);
                
                // 设置连接超时
                const timeout = setTimeout(() => {
                    if (ws && ws.readyState === WebSocket.CONNECTING) {
                        addLog('连接超时，关闭连接', 'error');
                        ws.close();
                    }
                }, 10000);

                ws.onopen = function() {
                    clearTimeout(timeout);
                    addLog('✅ WebSocket连接成功！', 'success');
                    updateStatus('✅ WebSocket已连接', 'connected');
                    document.getElementById('connectBtn').disabled = true;
                    document.getElementById('disconnectBtn').disabled = false;
                    connectionAttempts = 0;
                };

                ws.onmessage = function(event) {
                    addLog(`📨 收到消息: ${event.data}`, 'success');
                    
                    try {
                        const data = JSON.parse(event.data);
                        addLog(`📊 解析后的数据: ${JSON.stringify(data, null, 2)}`, 'info');
                    } catch (e) {
                        addLog('消息不是JSON格式', 'info');
                    }
                };

                ws.onerror = function(error) {
                    clearTimeout(timeout);
                    addLog('❌ WebSocket连接错误', 'error');
                    addLog(`错误详情: ${JSON.stringify({
                        readyState: ws.readyState,
                        url: ws.url,
                        error: error
                    }, null, 2)}`, 'error');
                    
                    updateStatus('❌ WebSocket连接错误', 'disconnected');
                };

                ws.onclose = function(event) {
                    clearTimeout(timeout);
                    addLog(`🔌 WebSocket连接关闭`, 'info');
                    addLog(`关闭详情: 代码=${event.code}, 原因="${event.reason}", 干净关闭=${event.wasClean}`, 'info');
                    
                    updateStatus('❌ WebSocket已断开', 'disconnected');
                    document.getElementById('connectBtn').disabled = false;
                    document.getElementById('disconnectBtn').disabled = true;

                    // 自动重试连接（如果不是手动断开且未超过重试次数）
                    if (event.code !== 1000 && connectionAttempts < maxRetries) {
                        addLog(`将在3秒后自动重试连接...`, 'info');
                        setTimeout(() => {
                            connectWebSocket();
                        }, 3000);
                    }
                };

            } catch (error) {
                addLog(`创建WebSocket失败: ${error.message}`, 'error');
                updateStatus('❌ 创建失败', 'disconnected');
            }
        }

        // 断开WebSocket
        function disconnectWebSocket() {
            if (ws) {
                addLog('手动断开WebSocket连接', 'info');
                ws.close(1000, '用户手动断开');
            }
        }

        // 发送测试消息
        function sendTestMessage() {
            const message = document.getElementById('messageInput').value.trim();
            if (!message) {
                addLog('请输入测试消息', 'error');
                return;
            }

            if (!ws || ws.readyState !== WebSocket.OPEN) {
                addLog('WebSocket未连接，无法发送消息', 'error');
                return;
            }

            try {
                // 构造测试消息
                const testMessage = {
                    textInput: message,
                    sessionId: Date.now().toString()
                };

                ws.send(JSON.stringify(testMessage));
                addLog(`📤 发送消息: ${JSON.stringify(testMessage)}`, 'success');
                document.getElementById('messageInput').value = '';
            } catch (error) {
                addLog(`发送消息失败: ${error.message}`, 'error');
            }
        }

        // 键盘事件处理
        function handleKeyPress(event) {
            if (event.key === 'Enter') {
                sendTestMessage();
            }
        }

        // 清空日志
        function clearLog() {
            document.getElementById('log').innerHTML = '';
            addLog('日志已清空', 'info');
        }

        // 页面加载完成后的初始化
        window.onload = function() {
            addLog('WebSocket调试工具已启动', 'info');
            addLog('点击"连接"按钮开始测试WebSocket连接', 'info');
            
            // 检查浏览器是否支持WebSocket
            if (typeof WebSocket === 'undefined') {
                addLog('❌ 浏览器不支持WebSocket', 'error');
                updateStatus('❌ 浏览器不支持WebSocket', 'disconnected');
            } else {
                addLog('✅ 浏览器支持WebSocket', 'success');
            }
        };

        // 页面关闭时清理WebSocket连接
        window.onbeforeunload = function() {
            if (ws) {
                ws.close();
            }
        };
    </script>
</body>
</html>
